#include <iostream>
#include <string>

#include "WrapperRegistry.h"

#include "luawrapper.hpp"
#include "luawrapperutil.hpp"

#include "FlightPath.h"

void showMemoryUsage(lua_State *L, char *msg)
{
	int memoryInUseKB = lua_gc(L, LUA_GCCOUNT, 0);
	int memoryInUseRemainBytes = lua_gc(L, LUA_GCCOUNTB, 0);

	size_t memoryInUse = memoryInUseKB * 1000 + memoryInUseRemainBytes;

	std::cout << "[" << msg << "] " << "Memory In Use : " << memoryInUse << " Bytes" << std::endl;
}


FlightPath *createFlightPath(lua_State *L)
{
	lua_getglobal(L, "createFlightPath");

	if (lua_pcall(L, 0, 1, 0) != LUA_OK)
	{
		std::cout << lua_tostring(L, -1) << std::endl;
		lua_pop(L, 1);
		return 0;
	}

	FlightPath *path = luaW_check<FlightPath>(L, -1);
	//luaW_release(L, path);

	showMemoryUsage(L, "In Use");
	lua_pop(L, 1);

	return path;
}

#define TEST_GC 0 


int main() 
{
	lua_State* L = luaL_newstate();
	luaL_openlibs(L);

	WrapperRegistry::openAll(L);

	if (luaL_loadfile(L, "test.lua")) 
	{
		std::cout << lua_tostring(L, -1) << std::endl;
	}

	if (lua_pcall(L, 0, 0, 0))
		std::cout << lua_tostring(L, -1) << std::endl;

#if TEST_GC
	for (int i = 0; i < 1000; ++i)
	{
		showMemoryUsage(L, "Before");
		auto path = createFlightPath(L);
		lua_gc(L, LUA_GCCOLLECT, 0);
		showMemoryUsage(L, "After");
	}
#endif

	return 0;
}